package cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformauth.vo.PlatformAuthSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.controller.admin.platformstore.vo.PlatformStoreSaveReqVO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformauth.PlatformAuthDO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformconfig.PlatformConfigDO;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformstore.PlatformStoreDO;
import cn.iocoder.yudao.module.crossborder.platform.service.platformauth.PlatformAuthService;
import cn.iocoder.yudao.module.crossborder.platform.service.platformconfig.PlatformConfigService;
import cn.iocoder.yudao.module.crossborder.platform.service.platformstore.PlatformStoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Amazon店铺设置服务
 * 基于现有架构实现Amazon店铺的完整设置流程
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class AmazonStoreSetupService {

    @Resource
    private PlatformConfigService platformConfigService;
    
    @Resource
    private PlatformStoreService platformStoreService;
    
    @Resource
    private PlatformAuthService platformAuthService;

    private static final String AMAZON_PLATFORM_CODE = "amazon";

    /**
     * 创建Amazon店铺
     *
     * @param storeConfig 店铺配置
     * @return 创建结果
     */
    public Map<String, Object> createAmazonStore(Map<String, Object> storeConfig) {
        log.info("创建Amazon店铺: config={}", storeConfig);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 获取Amazon平台配置
            PlatformConfigDO platformConfig = platformConfigService.getPlatformConfigByCode(AMAZON_PLATFORM_CODE);
            if (platformConfig == null) {
                result.put("success", false);
                result.put("message", "Amazon平台配置不存在，请先配置Amazon平台");
                return result;
            }
            
            // 2. 创建店铺记录
            PlatformStoreSaveReqVO storeReqVO = new PlatformStoreSaveReqVO();
            storeReqVO.setPlatformId(platformConfig.getId());
            storeReqVO.setName((String) storeConfig.get("storeName"));
            storeReqVO.setCode((String) storeConfig.get("storeId"));
            storeReqVO.setRegion((String) storeConfig.get("region"));
            storeReqVO.setMarketplaceId((String) storeConfig.get("marketplaceId"));
            storeReqVO.setStatus(1); // 启用状态
            
            Long newStoreId = platformStoreService.createPlatformStore(storeReqVO);
            
            // 3. 创建授权记录
            PlatformAuthSaveReqVO authReqVO = new PlatformAuthSaveReqVO();
            authReqVO.setPlatformId(platformConfig.getId());
            authReqVO.setStoreId(newStoreId);
            authReqVO.setAuthType(1); // OAuth2
            authReqVO.setClientId((String) storeConfig.get("clientId"));
            authReqVO.setClientSecret((String) storeConfig.get("clientSecret"));
            authReqVO.setScope("sellingpartnerapi::notifications");
            authReqVO.setAuthStatus(0); // 未授权状态
            authReqVO.setAutoRefresh(true);
            
            Long authId = platformAuthService.createPlatformAuth(authReqVO);
            
            result.put("success", true);
            result.put("storeId", newStoreId);
            result.put("authId", authId);
            result.put("message", "Amazon店铺创建成功");
            
        } catch (Exception e) {
            log.error("创建Amazon店铺失败", e);
            result.put("success", false);
            result.put("message", "创建失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取Amazon授权URL
     *
     * @param storeId 店铺ID
     * @param redirectUri 回调地址
     * @return 授权URL
     */
    public String getAmazonAuthUrl(Long storeId, String redirectUri) {
        log.info("获取Amazon授权URL: storeId={}, redirectUri={}", storeId, redirectUri);
        
        try {
            // 1. 获取店铺信息
            PlatformStoreDO store = platformStoreService.getPlatformStore(storeId);
            if (store == null) {
                log.error("店铺不存在: storeId={}", storeId);
                return null;
            }
            
            // 2. 获取授权配置
            PlatformAuthDO auth = platformAuthService.getPlatformAuthByStoreId(storeId);
            if (auth == null) {
                log.error("授权配置不存在: storeId={}", storeId);
                return null;
            }
            
            // 3. 构建Amazon授权URL
            String baseUrl = "https://sellercentral.amazon.com/apps/authorize/consent";
            String authUrl = String.format("%s?client_id=%s&scope=%s&response_type=code&redirect_uri=%s&state=%s",
                    baseUrl,
                    auth.getClientId(),
                    auth.getScope(),
                    redirectUri,
                    storeId);
            
            log.info("生成Amazon授权URL成功: storeId={}, authUrl={}", storeId, authUrl);
            return authUrl;
            
        } catch (Exception e) {
            log.error("获取Amazon授权URL失败", e);
            return null;
        }
    }

}
